# -*- coding: utf-8 -*-

import json
import subprocess


class DockerPsInfo(object):
    def __init__(self, names="", state=""):
        self.names = names  # 容器名称
        self.state = state  # 状态 exited
        self.createdAt = ""  # 创建时间
        self.id = ""  # 容器id
        self.image = ""  # 镜像名称
        self.runningFor = ""  # 运行时长  4 months ago

    # gvo_docker_ps{containerId="0",name=""} Up 4 weeks  Summary
    def print_metrics(self):
        return "gvo_docker_ps{name=\"%s\",createdAt=\"%s\"," \
               "image=\"%s\"} %s" % (
                   self.names, self.createdAt, self.image, self.state)


class DockerPsCollector(object):

    @classmethod
    def collector(clazz):
        rep = subprocess.run("docker ps -a --format json", shell=True, timeout=10000, encoding="utf-8",
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if rep.returncode != 0:
            return None

        lines = rep.stdout.splitlines()
        if len(lines) <= 0:
            return None

        results = []
        for line in lines:
            json_obj = json.loads(line)
            info = DockerPsInfo(json_obj['Names'], json_obj["State"])
            info.image = json_obj["Image"]
            info.id = json_obj["ID"]
            info.runningFor = json_obj["RunningFor"]
            info.createdAt = json_obj["CreatedAt"]
            results.append(info)

        return results

    @classmethod
    def metrics(clazz):
        docker_ps_info_list = clazz.collector()
        if docker_ps_info_list is None or len(docker_ps_info_list) == 0:
            return ""

        metrics_str = "# TYPE gvo_docker_ps summary \n"
        for item in docker_ps_info_list:
            metrics_str += item.print_metrics() + "\n"

        return metrics_str

# if __name__ == '__main__':
#     print(DockerPsCollector.metrics())
